﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Reflection;
using System.Web.Http;
using TomNet.IMSC.Core.Contracts.Account;
using TomNet.IMSC.Core.Contracts.Common;
using TomNet.IMSC.Core.Contracts.NewHouse;
using TomNet.IMSC.Core.Contracts.Organization;
using TomNet.IMSC.Model.DbModels.NewHouse;
using TomNet.IMSC.Web.Common;
using TomNet.IMSC.Web.Filters;
using TomNet.IMSC.Web.Models.ApiParams;
using TomNet.Utility.Data;
using TomNet.Web.Mvc.UI;
using TomNet.Web.WebApi;

namespace TomNet.IMSC.Web.Controllers.API
{

    [Description("API-新房")]
    [ApiAuthentication]
    public class NewHouseController : BaseApiController
    {
        public INewHouseRunningsContract NewHouseRunningsContract { get; set; }
        public IBuildingsContract BuildingsContract { get; set; }
        public IBuildingTopContract BuildingTopContract { get; set; }
        public IHouseTypeContract HouseTypeContract { get; set; }
        public IHouseTypeTagContract HouseTypeTagContract { get; set; }
        public IImagesContract ImagesContract { get; set; }
        public IAreaContract AreaContract { get; set; }
        public IBuildingsBrokerageGroupContract BuildingsBrokerageGroupContract { set; get; }
        public IPropertyConsultantContract PropertyConsultantContract { set; get; }
        public IModifyBuildingBrokerageLogContract ModifyBuildingBrokerageLogContract { set; get; }
        public IDictionaryContract DictionaryContract { set; get; }
        public IUsersContract UsersContract { set; get; }
        public IUsersRolesContract UsersRolesContract { set; get; }
        public ICustomerContract CustomerContract { get; set; }
        public ICustomerPhoneContract CustomerPhoneContract { get; set; }
        public IIntermediaryContract IntermediaryContract { get; set; }
        public IIntermediaryStaffContract IntermediaryStaffContract { get; set; }
        public IBrokerageRunningsContract BrokerageRunningsContract { get; set; }
        public IBrokerageSettleAccountsRunningsContract BrokerageSettleAccountsRunningsContract { get; set; }
        public IMessageBoardsContract MessageBoardsContract { get; set; }
        public IStaffContract StaffContract { get; set; }
        public IBuildingBuildingTypeContract BuildingBuildingTypeContract { get; set; }



        //新房====================================================================================================

        [Description("API-新房列表")]
        public IHttpActionResult ttGetBuildingsList([FromBody]BuildingsParamsModel entity)
        {
            //获取UserID
            int userid = BaseWebApiExt.GetUserIDByToken();

            //获取相关信息
            var userModel = UsersContract.GetByKey(userid);//经纪人
            var query = from a in BuildingsContract.Entities
                        join b in AreaContract.Entities on a.AreaID equals b.Id
                        where a.IsDeleted == false && a.State == 1 && (b.ParentID == userModel.CityID || entity.BuildingTypeID==2)
                        select new 
                        {
                            Address = a.Address,
                            AgentID = a.AgentID,
                            AreaID = a.AreaID,
                            AveragePrice = a.AveragePrice,
                            AwardDescription = a.AwardDescription,
                            BandSawBrokerage = a.BandSawBrokerage,
                            BandSawRules = a.BandSawRules,
                            BrandAdvantage = a.BrandAdvantage,
                            BuildingClass = a.BuildingClass,
                            BuildingInfo = a.BuildingInfo,
                            BuildingTypeID = a.BuildingTypeID,
                            CarNumber = a.CarNumber,
                            Characteristic = a.Characteristic,
                            City = b.ParentID,
                            CommissionAccount = a.CommissionAccount,
                            CooperateBeginTime = a.CooperateBeginTime,
                            CooperateEndTime = a.CooperateEndTime,
                            CooperativeHousing = a.CooperativeHousing,
                            CoveredArea = a.CoveredArea,
                            CreatedTime = a.CreatedTime,
                            DecorationCondition = a.DecorationCondition,
                            Developer = a.Developer,
                            DeveloperBrand = a.DeveloperBrand,
                            DevelopersRules = a.DevelopersRules,
                            District = a.District,
                            FilingRules = a.FilingRules,
                            GreeningRatio = a.GreeningRatio,
                            HaveProductComparison = a.HaveProductComparison,
                            HouseTypeArea = a.HouseTypeArea,
                            Id = a.Id,
                            IsDeleted = a.IsDeleted,
                            IsLocked = a.IsLocked,
                            LaunchTime = a.LaunchTime,
                            LeaseBrokerage = a.LeaseBrokerage,
                            LeasePrice = a.LeasePrice,
                            LetSellType = a.LetSellType,
                            LivingFacilities = a.LivingFacilities,
                            MediumOfCommunicationStaffID = a.MediumOfCommunicationStaffID,
                            Name = a.Name,
                            OldID = a.OldID,
                            OpeningTime = a.OpeningTime,
                            ParkingRatio = a.ParkingRatio,
                            PlotRatio = a.PlotRatio,
                            PriceAdvantage = a.PriceAdvantage,
                            PropertyManagementCompany = a.PropertyManagementCompany,
                            PropertyManagementFee = a.PropertyManagementFee,
                            PropertyRight = a.PropertyRight,
                            Province = a.Province,
                            RegionalDevelopment = a.RegionalDevelopment,
                            Remark = a.Remark,
                            SchoolDistrict = a.SchoolDistrict,
                            SellingBrokerage = a.SellingBrokerage,
                            SellingPrice = a.SellingPrice,
                            ShowIndex = a.ShowIndex,
                            StarTarget = a.StarTarget,
                            StarTargetRemark = a.StarTargetRemark,
                            State = a.State,
                            StationedStaffID = a.StationedStaffID,
                            SubscriptionDeadline = a.SubscriptionDeadline,
                            TotalHouseholds = a.TotalHouseholds,
                            TransactionRules = a.TransactionRules,
                            Transportation = a.Transportation,
                            X = a.X,
                            Y = a.Y
                        };

            //条件搜索
            if (!string.IsNullOrWhiteSpace(entity.KeyWord))
            {
                query = query.Where(m => m.Name.Contains(entity.KeyWord));
            }

            //类型选择
            if (!string.IsNullOrWhiteSpace(entity.AreaID))
            {
                query = query.Where(m => m.AreaID.Equals(entity.AreaID));
            }
            if (entity.BuildingTypeID > 0)
            {
                //query = query.Where(m => m.BuildingTypeID == entity.BuildingTypeID);
                if (entity.BuildingTypeID == 3 || entity.BuildingTypeID == 4)
                {
                    query = query.Where(m => BuildingBuildingTypeContract.Entities.Count(p => p.BuildingID == m.Id && (p.BuildingTypeID == 3 || p.BuildingTypeID == 4)) > 0);
                }
                else
                {
                    query = query.Where(m => BuildingBuildingTypeContract.Entities.Count(p => p.BuildingID == m.Id && p.BuildingTypeID == entity.BuildingTypeID) > 0);
                }

            }

            var list = (from m in query
                        //join n in BuildingTopContract.Entities on m.Id equals n.UnionID into tempb
                        //from b in tempb.DefaultIfEmpty()

                        //where  (b != null && b.UnionModule == 1 && DateTime.Now > b.BeginTime && DateTime.Now < b.EndTime && !b.IsDeleted)//新房
                        //|| b == null //没有置顶
                        

                        let img = (from m1 in ImagesContract.Entities where m1.GroupID == 1 && m1.InterfixID == m.Id && m1.IsDeleted == false orderby m1.Id select (m1.ImagePath + m1.FileName)).FirstOrDefault()
                                                                        
                        select new BuildingsListModel
                        {
                            Id = m.Id,
                            Name = m.Name,
                            SellingPrice = m.SellingPrice,//售价
                            SellingBrokerage = m.SellingBrokerage,//销售佣金
                            CommissionAccount = m.CommissionAccount,//佣金帐期
                            ImagePath = (img == null) ? "" : img.Replace(@"\", "/"),
                            CreatedTime = m.CreatedTime,
                            //MainShowIndex = m.ShowIndex,

                            IsTop = BuildingTopContract.Entities.Count(b=>b.UnionModule==1 && DateTime.Now > b.BeginTime && DateTime.Now < b.EndTime && !b.IsDeleted && b.UnionID == m.Id),//是否置顶
                            TopShowIndex = BuildingTopContract.Entities.Count(b => b.UnionModule == 1 && DateTime.Now > b.BeginTime && DateTime.Now < b.EndTime && !b.IsDeleted && b.UnionID == m.Id) == 0? m.ShowIndex : BuildingTopContract.Entities.FirstOrDefault(b => b.UnionModule == 1 && DateTime.Now > b.BeginTime && DateTime.Now < b.EndTime && !b.IsDeleted && b.UnionID == m.Id).ShowIndex,
                        });

            //数据总数
            var total = list.Count();

            //默认给一个排序的字段
            //list = list.OrderByDescending(m => m.ShowIndex);
            list = list.OrderByDescending(x => x.IsTop).ThenBy(m => m.TopShowIndex);//.ThenByDescending(m => m.CreatedTime);

            //分页(假如total == 0，则取消分页查询，提高性能)
            list = total > 0 ? list.Skip((entity.PageIndex - 1) * entity.PageSize).Take(entity.PageSize)
                : Enumerable.Empty<BuildingsListModel>().AsQueryable();// null;

            
            var result = new AjaxResultRow("成功", AjaxResultType.Success, list.ToList(),total);
            return Token(result, "");

        }

        [AllowAnonymous]
        [Description("API-新房内容")]
        public IHttpActionResult ttGetBuildingModel([FromBody]BuildingInfoParamsModel entity)
        {

            var model = BuildingsContract.Entities.Where(m => m.Id == entity.BuildingID).FirstOrDefault();

            if (model != null)
            {
                ExtMethod.HandleModelValue<Buildings>(model);//处理null

                var query = new BuildingInfoModel();

                //基本信息
                query.BaseInfo = model;
                
                //封面集合
                var tempList = (from m1 in ImagesContract.Entities where m1.GroupID == 1 && m1.InterfixID == model.Id && m1.IsDeleted == false orderby m1.Id select (m1.ImagePath + m1.FileName));
                query.ImageList = tempList.Select(m => (m == null) ? "" : m.Replace(@"\", "/")).ToList();//图片路径

                //区域名称
                query.AreaName = (from m1 in AreaContract.Entities where m1.Id == model.AreaID select m1.Name).FirstOrDefault();
                query.AreaName = query.AreaName == null ? "" : query.AreaName;

                //是否置顶
                var topModel = BuildingTopContract.Entities.Where(b => b.UnionID == model.Id && b.UnionModule == 1 && DateTime.Now > b.BeginTime && DateTime.Now < b.EndTime && !b.IsDeleted).FirstOrDefault();
                query.IsTop = topModel == null ? 0 : 1;//是否置顶


                //户型推荐
                query.HouseTypeList = (from m2 in HouseTypeContract.Entities
                                       where m2.BuildingID == model.Id && m2.IsDeleted == false
                                       let img = (from m6 in ImagesContract.Entities where m6.GroupID == 2 && m6.InterfixID == m2.Id && m6.IsDeleted == false orderby m6.Id select (m6.ImagePath + m6.FileName)).FirstOrDefault()
                                       select new HouseTypeInfoModel
                                       {
                                           Id = m2.Id,
                                           BuildingID = m2.BuildingID,
                                           Name = m2.Name,
                                           Area = m2.Area,
                                           Room = m2.Room,
                                           Hall = m2.Hall,
                                           Toilet = m2.Toilet,
                                           Inventory = m2.Inventory,
                                           SalesVolume = m2.SalesVolume,
                                           Price = m2.Price,
                                           Preferential = m2.Preferential,
                                           Orientations = m2.Orientations,
                                           DecorationCondition = m2.DecorationCondition,
                                           Reason = m2.Reason,
                                           ShowIndex = m2.ShowIndex,
                                           Remark = m2.Remark,

                                           ImagePath = (img == null) ? "" : img.Replace(@"\", "/"),

                                           HouseTypeTagList = (
                                               from a in HouseTypeTagContract.Entities
                                               join b in DictionaryContract.Entities
                                               on a.DictionaryID equals b.Id
                                               where a.HouseTypeID == m2.Id
                                               select b.Value
                                           ).ToList()//户型标签集合

                                       }).ToList();

                query.BuildingsBrokerageGroupList = BuildingsBrokerageGroupContract.Entities.Where(m3 => m3.BuildingID == model.Id).ToList();//楼盘佣金分组
                query.PropertyConsultantList = PropertyConsultantContract.Entities.Where(m4 => m4.BuildingID == model.Id && m4.IsDeleted == false).ToList();//置业顾问
                query.ModifyBuildingBrokerageLogList = ModifyBuildingBrokerageLogContract.Entities.Where(m5 => m5.BuildingID == model.Id && m5.IsDeleted == false).ToList();//楼盘修改佣金日志

                //分享信息
                query.HeadTitle = model.Name;
                query.ViceTitle = model.Name;
                query.SharedInfo = model.BuildingInfo;
                query.SharedIcon = "";
                query.SharedURL = CommonInof.GetUrl() + "NewHouse/Buildings/mmBuildingModel?Id=" + entity.BuildingID;
                query.BackUp = "";


                var result = new AjaxResult("成功", AjaxResultType.Success, query);
                return Token(result, "");
            }
            else
            {
                var result = new AjaxResult("失败", AjaxResultType.Error);
                return Token(result, "");
            }

        }
        

        //报备流程====================================================================================================

        [Description("API-新建报备订单")]
        public IHttpActionResult ttInsertRunningsModel([FromBody]RunningsParamsModel entity)
        {

            if (entity == null)
            {
                var result = new AjaxResult("添加失败", AjaxResultType.Error);
                return Token(result, "");
            }

            //获取UserID
            int userid = BaseWebApiExt.GetUserIDByToken();

            //获取相关信息
            var userModel = UsersContract.GetByKey(userid);//经纪人
            var buildingsModel = BuildingsContract.GetByKey(entity.BuildingID);//楼盘
            var intermediaryModel = IntermediaryContract.GetByKey(userModel.IntermediaryID);//中介
            var customerModel = CustomerContract.GetByKey(entity.CustomerID);//客户
            var customerPhoneModel = CustomerPhoneContract.GetByKey(entity.CustomerPhoneID);//客户电话
            var intermediaryStaffModel = IntermediaryStaffContract.Entities.Where(m => m.IntermediaryID == userModel.IntermediaryID && m.ModuleID == 1).FirstOrDefault();//新房销售

            NewHouseRunnings model = new NewHouseRunnings();
            model.BuildingID = buildingsModel.Id;
            model.BuildingName = buildingsModel.Name;
            model.IntermediaryID = intermediaryModel.Id;
            model.IntermediaryName = intermediaryModel.Name;
            model.UserID = userid;
            model.UserName = userModel.Name;
            model.UserPhone = userModel.Phone;
            model.CustomerID = customerModel.Id;
            model.CustomerName = customerModel.Name;
            model.CustomerPhone = customerPhoneModel.Phone;
            model.FilingTime = DateTime.Now;
            model.OriginStaffID = buildingsModel.MediumOfCommunicationStaffID;//渠道人员ID
            model.SellStaffID = intermediaryStaffModel.StaffID;//销售人员ID
            model.AgentID = buildingsModel.AgentID;

            //时间初始化
            model.FilingAuditingTime = DateTime.Now;
            model.SubscribeTime = DateTime.Now;
            model.DownPaymentTime = DateTime.Now;
            model.PutOnRecordTime = DateTime.Now;
            model.CompleteTime = DateTime.Now;
            model.ReturnHouseTime = DateTime.Now;
            model.ReturnHouseAuditingTime = DateTime.Now;
            model.BandSawTime = DateTime.Now;

            model.State = 1;
            model.ReturnState = 1;

            int count = NewHouseRunningsContract.Insert(model);

            if (count > 0)
            {
                var result = new AjaxResult("添加成功", AjaxResultType.Success);
                return Token(result, "");
            }
            else
            {
                var result = new AjaxResult("添加失败", AjaxResultType.Error);
                return Token(result, "");
            }


        }


        [Description("API-获取报备列表")]
        public IHttpActionResult ttGetRunningsList([FromBody]RunningsListModel entity)
        {
            //获取UserID
            int userid = BaseWebApiExt.GetUserIDByToken();
            bool IsDianZhang = UsersRolesContract.Entities.Count(p => p.IntermediaryRoleID == 1 && p.UserID == userid) > 0;
            bool IsHide = IntermediaryContract.GetByKey(UsersContract.GetByKey(userid).IntermediaryID).IsLocked;
            var query = NewHouseRunningsContract.Entities;

            //判断用户角色是否为店长
            if (UsersRolesContract.Entities.Where(m => m.UserID == userid && m.IntermediaryRoleID > 0).FirstOrDefault() != null)
            {
                var userModel = UsersContract.GetByKey(userid);
                query = query.Where(m => m.IntermediaryID == userModel.IntermediaryID);//查看当前门店的报备
            }
            else
            {
                query = query.Where(m => m.UserID == userid);//查看经纪人自己报备的
            }
            

            //数据总数
            var total = query.Count();

            //默认给一个排序的字段
            query = query.OrderByDescending(m => m.FilingTime);

            //分页(假如total == 0，则取消分页查询，提高性能)
            query = total > 0 ? query.Skip((entity.PageIndex - 1) * entity.PageSize).Take(entity.PageSize)
                : Enumerable.Empty<NewHouseRunnings>().AsQueryable();


            List<RunningsListShowModel> list = new List<RunningsListShowModel>();

            foreach (var item in query)
            {
                var temp = new RunningsListShowModel();
                temp.Id = item.Id;
                temp.CustomerName = item.CustomerName;
                temp.CustomerPhone = IsDianZhang || !IsHide ? item.CustomerPhone : item.CustomerPhone.Substring(0, 3) + "****" + item.CustomerPhone.Substring(7);
                temp.BuildingName = item.BuildingName;
                temp.UserName = item.UserName;

                //1 报备待审 2 报备通过 3 报备驳回 4 已带看 5 已交订金 6 已付首款 7 已备案 8 已完成 
                switch (item.State)
                {
                    case 1:
                        temp.State = "报备待审";
                        temp.OperTime = item.FilingTime.ToString("yy-MM-dd HH:mm");
                        break;
                    case 2:
                        temp.State = "报备通过";
                        temp.OperTime = item.FilingAuditingTime.ToString("yy-MM-dd HH:mm");
                        break;
                    case 3:
                        temp.State = "报备驳回";
                        temp.OperTime = item.FilingAuditingTime.ToString("yy-MM-dd HH:mm");
                        break;
                    case 4:
                        temp.State = "已带看";
                        temp.OperTime = item.BandSawTime.ToString("yy-MM-dd HH:mm");
                        break;
                    case 5:
                        temp.State = "已交订金";
                        temp.OperTime = item.SubscribeTime.ToString("yy-MM-dd HH:mm");
                        break;
                    case 6:
                        temp.State = "已付首款";
                        temp.OperTime = item.DownPaymentTime.ToString("yy-MM-dd HH:mm");
                        break;
                    case 7:
                        temp.State = "已备案";
                        temp.OperTime = item.PutOnRecordTime.ToString("yy-MM-dd HH:mm");
                        break;
                    case 8:
                        temp.State = "已完成";
                        temp.OperTime = item.CompleteTime.ToString("yy-MM-dd HH:mm");
                        break;
                    default:
                        temp.State = "";
                        temp.OperTime = "";
                        break;
                }

                //退房
                if (item.ReturnState == 2)
                {
                    temp.State = "退房待审";
                    temp.OperTime = item.ReturnHouseTime.ToString("yy-MM-dd HH:mm");
                }
                if (item.ReturnState == 3)
                {
                    temp.State = "已退房";
                    temp.OperTime = item.ReturnHouseAuditingTime.ToString("yy-MM-dd HH:mm");
                }

                list.Add(temp);
            }
            

            var result = new AjaxResultRow("成功", AjaxResultType.Success, list, total);
            return Token(result, "");

        }


        [Description("API-查看报备订单")]
        public IHttpActionResult ttGetRunningModel([FromBody]NewHouseRunnings entity)
        {

            var model = NewHouseRunningsContract.GetByKey(entity.Id);
            int userid = BaseWebApiExt.GetUserIDByToken();
            bool IsDianZhang = UsersRolesContract.Entities.Count(p => p.IntermediaryRoleID == 1 && p.UserID == userid) > 0;
            bool IsHide = IntermediaryContract.GetByKey(UsersContract.GetByKey(userid).IntermediaryID).IsLocked;
            //记录状态 State： 1 报备待审 2 报备通过 3 报备驳回 4 已带看 5 已交订金 6 已付首款 7 已备案 8 已完成 
            //退房状态 ReturnState: 1 默认 2 退房待审 3 已退房
            //模板选择： 1 报备+通过 2 报备+未通过 3 带看 4 完成
            //图标形状： 1 进行中，橘黄色 2 已完成，绿色 3 等待，灰色 4 拒绝，红色
            //颜色值： 橘黄色=#F57035 绿色=#3AB394 灰色 =#B3B3B3 红色=#F40001

            if (model != null)
            {
                ExtMethod.HandleModelValue<NewHouseRunnings>(model);//处理null

                var query = new NewHouseRunningsInfoModel();
                query.Id = model.Id;
                query.BuildingName = model.BuildingName;
                query.UserName = model.UserName;
                query.UserPhone = model.UserPhone;
                query.CustomerName = model.CustomerName;
                query.CustomerPhone = IsDianZhang || (!IsHide) ? model.CustomerPhone : model.CustomerPhone.Substring(0, 3) + "****" + model.CustomerPhone.Substring(7);
                query.State = model.State;

                query.NewHouseRunningsInfoShowList = new List<NewHouseRunningsInfoShowModel>();//流水步骤集合

                #region 1 报备

                var FilingModel = new NewHouseRunningsInfoShowModel();
                FilingModel.SortID = 1;

                switch (model.State)
                {
                    case 1://报备待审
                        FilingModel.StyleID = 1;//模板1
                        FilingModel.ModuleName = "报备";
                        FilingModel.ModuleNameColor = "#F57035";//橘黄色
                        FilingModel.ModuleIcon = 1;//进行中
                        FilingModel.ModuleIconColor = "#F57035";//橘黄色
                        FilingModel.Title = "报备客户";
                        FilingModel.OperTime = model.FilingTime.ToString("yy-MM-dd HH:mm");
                        FilingModel.ViceTitle = "等待审核";
                        FilingModel.ViceTitleColor = "#F57035";//橘黄色
                        break;
                    case 3://报备驳回
                        FilingModel.StyleID = 2;//模板2
                        FilingModel.ModuleName = "报备";
                        FilingModel.ModuleNameColor = "#F40001";//红色
                        FilingModel.ModuleIcon = 4;//拒绝
                        FilingModel.ModuleIconColor = "#F40001";//红色
                        FilingModel.Title = "报备客户";
                        FilingModel.OperTime = model.FilingAuditingTime.ToString("yy-MM-dd HH:mm");
                        FilingModel.ViceTitle = "审核未通过";
                        FilingModel.ViceTitleColor = "#F40001";//红色
                        FilingModel.FilingAuditingRemark = model.FilingAuditingRemark == null ? "无" : model.FilingAuditingRemark;//报备审核说明
                        break;
                    case 2://报备通过
                    case 4://已带看
                    case 5://已交订金
                    case 6://已付首款
                    case 7://已备案
                    case 8://已完成
                        FilingModel.StyleID = 1;//模板1
                        FilingModel.ModuleName = "报备";
                        FilingModel.ModuleNameColor = "#3AB394";//绿色
                        FilingModel.ModuleIcon = 2;//已完成
                        FilingModel.ModuleIconColor = "#3AB394";//绿色
                        FilingModel.Title = "报备客户";
                        FilingModel.OperTime = model.FilingAuditingTime.ToString("yy-MM-dd HH:mm");
                        FilingModel.ViceTitle = "审核通过";
                        FilingModel.ViceTitleColor = "#3AB394";//绿色
                        break;
                }

                query.NewHouseRunningsInfoShowList.Add(FilingModel);

                #endregion

                # region 2 带看

                var BandSawModel = new NewHouseRunningsInfoShowModel();
                BandSawModel.SortID = 2;

                switch (model.State)
                {
                    case 1://报备待审
                    case 3://报备驳回
                        BandSawModel.StyleID = 4;//模板4
                        BandSawModel.ModuleName = "带看";
                        BandSawModel.ModuleNameColor = "#B3B3B3";//灰色
                        BandSawModel.ModuleIcon = 3;//等待
                        BandSawModel.ModuleIconColor = "#B3B3B3";//灰色                        
                        break;
                    case 2://报备通过
                        BandSawModel.StyleID = 3;//模板3
                        BandSawModel.ModuleName = "带看";
                        BandSawModel.ModuleNameColor = "#F57035";//橘黄色
                        BandSawModel.ModuleIcon = 1;//进行中
                        BandSawModel.ModuleIconColor = "#F57035";//橘黄色
                        BandSawModel.Title = "可带看";
                        BandSawModel.OperTime = "";//带看时间
                        BandSawModel.ViceTitle = "";
                        BandSawModel.ViceTitleColor = "";
                        BandSawModel.IsCameraButton = 1;//有照相按钮
                        BandSawModel.GroupID = 3;//分组
                        BandSawModel.ImageType = 1;//带看单
                        BandSawModel.ImageRemark = "带看后请上传照片，\"客户带看单\"照片为必传照片，带看单必需有置业顾问、经纪人、项目经理签字，其他照片可以是\"客户与售楼员合影\"、\"客户与经纪人合影\"等等!";
                        BandSawModel.ImageList = ImagesContract.Entities.Where(m1 => m1.GroupID == 3 && m1.ImageType == 1 && m1.InterfixID == model.Id && m1.IsDeleted == false).ToList();//带看图片集合
                        BandSawModel.ViewButtonText = "查看\"客户带看单\"范例";//查看按钮文本
                        BandSawModel.ViewButtonValue = "";//查看按钮链接地址
                        break;
                    case 4://已带看
                    case 5://已交订金
                    case 6://已付首款
                    case 7://已备案
                    case 8://已完成
                        BandSawModel.StyleID = 3;//模板3
                        BandSawModel.ModuleName = "带看";
                        BandSawModel.ModuleNameColor = "#3AB394";//绿色
                        BandSawModel.ModuleIcon = 2;//已完成
                        BandSawModel.ModuleIconColor = "#3AB394";//绿色
                        BandSawModel.Title = "已带看";
                        BandSawModel.OperTime = model.BandSawTime.ToString("yy-MM-dd HH:mm"); ;//带看时间
                        BandSawModel.ViceTitle = "";
                        BandSawModel.ViceTitleColor = "";                        
                        BandSawModel.IsCameraButton = 1;//有照相按钮
                        BandSawModel.GroupID = 3;//分组
                        BandSawModel.ImageType = 1;//带看单
                        BandSawModel.ImageRemark = "带看后请上传照片，\"客户带看单\"照片为必传照片，带看单必需有置业顾问、经纪人、项目经理签字，其他照片可以是\"客户与售楼员合影\"、\"客户与经纪人合影\"等等!";
                        BandSawModel.ImageList = ImagesContract.Entities.Where(m1 => m1.GroupID == 3 && m1.ImageType == 1 && m1.InterfixID == model.Id && m1.IsDeleted == false).ToList();//带看图片集合
                        BandSawModel.IsViewButton = 1;//有查看按钮
                        BandSawModel.ViewButtonText = "查看\"客户带看单\"范例";//查看按钮文本
                        BandSawModel.ViewButtonValue = "";//查看按钮链接地址
                        break;
                }

                query.NewHouseRunningsInfoShowList.Add(BandSawModel);

                #endregion

                #region 3 认购

                var SubscribeModel = new NewHouseRunningsInfoShowModel();
                SubscribeModel.ModuleName = "认购";
                switch (model.State)
                {
                    case 1://报备待审
                    case 2://报备通过
                    case 3://报备驳回                    
                        SubscribeModel.StyleID = 4;//模板4         
                        SubscribeModel.ModuleNameColor = "#B3B3B3";//灰色
                        SubscribeModel.ModuleIcon = 3;//等待
                        SubscribeModel.ModuleIconColor = "#B3B3B3";//灰色                                                                   
                        break;
                    case 4://带看完成 待交定金
                        SubscribeModel.StyleID = 3;//模板3              
                        SubscribeModel.ModuleNameColor = "#F57035";//橘黄色
                        SubscribeModel.ModuleIcon = 1;//进行中
                        SubscribeModel.ModuleIconColor = "#F57035";//橘黄色
                        SubscribeModel.Title = "待交定金";
                        SubscribeModel.OperTime = "";//待交定金没有时间
                        SubscribeModel.ViceTitle = "";//副标题  定金金额  
                        SubscribeModel.ViceTitleColor = "";
                        SubscribeModel.IsCameraButton = 1;//有相机
                        SubscribeModel.GroupID = 3;//分组
                        SubscribeModel.ImageType = 2;//成交确认单                        
                        SubscribeModel.ImageRemark = "请上传\"认购确认单\"照片！";
                        SubscribeModel.ImageList = ImagesContract.Entities.Where(m1 => m1.GroupID == 3 && m1.ImageType == 2 && m1.InterfixID == model.Id && m1.IsDeleted == false).ToList();//成交图片集合
                        FilingModel.IsViewButton = 0;//没有查看按钮
                        break;
                    case 5://已交定金
                    case 6://已付首款
                    case 7://已备案
                    case 8://已完成
                        SubscribeModel.StyleID = 3;//模板3
                        SubscribeModel.ModuleNameColor = "#3AB394";//绿色
                        SubscribeModel.ModuleIcon = 2;//已完成
                        SubscribeModel.ModuleIconColor = "#3AB394";//绿色
                        SubscribeModel.Title = "已付定金";
                        SubscribeModel.OperTime = model.SubscribeTime.ToString("yy-MM-dd HH:mm"); ;//已付定金时间                        
                        SubscribeModel.ViceTitle = (model.BargainMoney / 10000).ToString("0.00") + "万元";//副标题  定金金额  
                        SubscribeModel.ViceTitleColor = "";
                        SubscribeModel.IsCameraButton = 0;//没有相机
                        SubscribeModel.GroupID = 3;//分组
                        SubscribeModel.ImageType = 2;//成交确认单
                        SubscribeModel.ImageRemark = "请上传\"认购确认单\"照片！";
                        SubscribeModel.ImageList = ImagesContract.Entities.Where(m1 => m1.GroupID == 3 && m1.ImageType == 2 && m1.InterfixID == model.Id && m1.IsDeleted == false).ToList();//成交图片集合
                        SubscribeModel.IsViewButton = 0;//没有查看按钮
                        break;
                }

                query.NewHouseRunningsInfoShowList.Add(SubscribeModel);

                #endregion

                #region 4 首付

                var DownPaymentModel = new NewHouseRunningsInfoShowModel();
                DownPaymentModel.SortID = 4;//排序
                DownPaymentModel.ModuleName = "首付";

                switch (model.State)
                {
                    case 1://报备待审                   
                    case 2://报备通过
                    case 3://报备驳回                  
                    case 4://已带看
                        DownPaymentModel.StyleID = 4;//模板4            
                        DownPaymentModel.ModuleNameColor = "#B3B3B3";//灰色
                        DownPaymentModel.ModuleIcon = 3;//等待
                        DownPaymentModel.ModuleIconColor = "#B3B3B3";//灰色
                        break;
                    case 5://已付定金  
                        if (model.ReturnState.Equals(3))//已退房
                        {
                            DownPaymentModel.StyleID = 1;//模板1
                            DownPaymentModel.ModuleNameColor = "#F40001";//红色
                            DownPaymentModel.ModuleIcon = 4;//拒绝
                            DownPaymentModel.ModuleIconColor = "#F40001";//红色
                            DownPaymentModel.Title = "已退房";
                            DownPaymentModel.OperTime = model.ReturnHouseAuditingTime.ToString("yy-MM-dd HH:mm"); ;//退房审核时间
                            DownPaymentModel.ViceTitle = "";//副标题  没有内容
                            DownPaymentModel.ViceTitleColor = "";//副标题  没有颜色 
                        }
                        else//正常
                        {
                            DownPaymentModel.StyleID = 1;//模板1
                            DownPaymentModel.ModuleNameColor = "#F57035";//橘黄色
                            DownPaymentModel.ModuleIcon = 1;//进行中
                            DownPaymentModel.ModuleIconColor = "#F57035";//橘黄色
                            DownPaymentModel.Title = "待交首付";
                            DownPaymentModel.OperTime = "";//待交首付没有时间
                            DownPaymentModel.ViceTitle = "";//副标题  没有内容
                            DownPaymentModel.ViceTitleColor = "";//副标题  没有颜色 
                        }                        
                        break;
                    case 6://已付首款
                    case 7://已备案
                    case 8://已完成
                        DownPaymentModel.StyleID = 1;//模板1
                        DownPaymentModel.ModuleNameColor = "#3AB394";//绿色
                        DownPaymentModel.ModuleIcon = 2;//已完成
                        DownPaymentModel.ModuleIconColor = "#3AB394";//绿色
                        DownPaymentModel.Title = "已交首付";
                        DownPaymentModel.OperTime = model.DownPaymentTime.ToString("yy-MM-dd HH:mm"); ;//首付时间
                        DownPaymentModel.ViceTitle = (model.DownPaymentMoney / 10000).ToString("0.00") + "万元";//副标题  已交首付金额   
                        DownPaymentModel.ViceTitleColor = "#F57035";//副标题  橘黄色                      
                        break;
                }

                query.NewHouseRunningsInfoShowList.Add(DownPaymentModel);

                #endregion

                #region 5 备案

                var PutOnRecordModel = new NewHouseRunningsInfoShowModel();
                PutOnRecordModel.ModuleName = "备案";
                PutOnRecordModel.SortID = 5;

                switch (model.State)
                {
                    case 1://报备待审
                    case 2://报备通过
                    case 3://报备驳回
                    case 4://已带看
                    case 5://已交订金
                        PutOnRecordModel.StyleID = 4;//模板4                        
                        PutOnRecordModel.ModuleNameColor = "#B3B3B3";//灰色
                        PutOnRecordModel.ModuleIcon = 3;//等待
                        PutOnRecordModel.ModuleIconColor = "#B3B3B3";//灰色                        
                        break;
                    case 6://已付首款
                        if (model.ReturnState.Equals(3))//已退房
                        {
                            PutOnRecordModel.StyleID = 1;//模板1
                            PutOnRecordModel.ModuleNameColor = "#F40001";//红色
                            PutOnRecordModel.ModuleIcon = 4;//拒绝
                            PutOnRecordModel.ModuleIconColor = "#F40001";//红色
                            PutOnRecordModel.Title = "已退房";
                            PutOnRecordModel.OperTime = model.ReturnHouseAuditingTime.ToString("yy-MM-dd HH:mm"); ;//退房审核时间
                            PutOnRecordModel.ViceTitle = "";//副标题  没有内容
                            PutOnRecordModel.ViceTitleColor = "";//副标题  没有颜色 
                        }
                        else//正常
                        {
                            PutOnRecordModel.StyleID = 3;//模板3
                            PutOnRecordModel.ModuleNameColor = "#F57035";//橘黄色
                            PutOnRecordModel.ModuleIcon = 1;//进行中
                            PutOnRecordModel.ModuleIconColor = "#F57035";//橘黄色
                            PutOnRecordModel.Title = "待备案";
                            PutOnRecordModel.OperTime = "";//备案时间
                            PutOnRecordModel.ViceTitle = "";
                            PutOnRecordModel.ViceTitleColor = "";
                            PutOnRecordModel.IsCameraButton = 1;//有照相按钮
                            PutOnRecordModel.GroupID = 3;//分组
                            PutOnRecordModel.ImageType = 3;//备案合同
                            PutOnRecordModel.ImageRemark = "请上传\"备案合同\"照片!";
                            PutOnRecordModel.ImageList = ImagesContract.Entities.Where(m1 => m1.GroupID == 3 && m1.ImageType == 3 && m1.InterfixID == model.Id && m1.IsDeleted == false).ToList();//备案图片集合
                            PutOnRecordModel.IsViewButton = 0;//没有查看按钮
                        }                            
                        break;
                    case 7://已备案
                    case 8://已完成
                        PutOnRecordModel.StyleID = 3;//模板3
                        PutOnRecordModel.ModuleNameColor = "#3AB394";//绿色
                        PutOnRecordModel.ModuleIcon = 2;//已完成
                        PutOnRecordModel.ModuleIconColor = "#3AB394";//绿色
                        PutOnRecordModel.Title = "已备案";
                        PutOnRecordModel.OperTime = model.PutOnRecordTime.ToString("yy-MM-dd HH:mm");//备案时间
                        PutOnRecordModel.ViceTitle = "";
                        PutOnRecordModel.ViceTitleColor = "";
                        PutOnRecordModel.IsCameraButton = 1;//有照相按钮
                        PutOnRecordModel.GroupID = 3;//分组
                        PutOnRecordModel.ImageType = 3;//带看单
                        PutOnRecordModel.ImageRemark = "带看后请上传照片，\"客户带看单\"照片为必传照片，带看单必需有置业顾问、经纪人、项目经理签字，其他照片可以是\"客户与售楼员合影\"、\"客户与经纪人合影\"等等!";
                        PutOnRecordModel.ImageList = ImagesContract.Entities.Where(m1 => m1.GroupID == 3 && m1.ImageType == 3 && m1.InterfixID == model.Id && m1.IsDeleted == false).ToList();//备案图片集合
                        PutOnRecordModel.IsViewButton = 0;//没有查看按钮
                        break;
                }

                query.NewHouseRunningsInfoShowList.Add(PutOnRecordModel);

                #endregion

                #region 6 完成

                var CompleteModel = new NewHouseRunningsInfoShowModel();
                CompleteModel.ModuleName = "完成";
                CompleteModel.SortID = 6;

                switch (model.State)
                {
                    case 1://报备待审
                    case 2://报备通过
                    case 3://报备驳回
                    case 4://已带看
                    case 5://已交订金
                    case 6://已付首款
                        CompleteModel.StyleID = 4;//模板4                        
                        CompleteModel.ModuleNameColor = "#B3B3B3";//灰色
                        CompleteModel.ModuleIcon = 3;//等待
                        CompleteModel.ModuleIconColor = "#B3B3B3";//灰色                        
                        break;
                    case 7://已备案
                    case 8://已完成
                        if (model.ReturnState.Equals(3))//已退房
                        {
                            CompleteModel.StyleID = 1;//模板1
                            CompleteModel.ModuleNameColor = "#F40001";//红色
                            CompleteModel.ModuleIcon = 4;//拒绝
                            CompleteModel.ModuleIconColor = "#F40001";//红色
                            CompleteModel.Title = "已退房";
                            CompleteModel.OperTime = model.ReturnHouseAuditingTime.ToString("yy-MM-dd HH:mm"); ;//退房审核时间
                            CompleteModel.ViceTitle = "";//副标题  没有内容
                            CompleteModel.ViceTitleColor = "";//副标题  没有颜色 
                        }
                        else//正常
                        {
                            CompleteModel.StyleID = 4;//模板4
                            CompleteModel.ModuleNameColor = "#3AB394";//绿色
                            CompleteModel.ModuleIcon = 2;//已完成
                            CompleteModel.ModuleIconColor = "#3AB394";//绿色
                        }
                        break;
                }

                query.NewHouseRunningsInfoShowList.Add(CompleteModel);

                #endregion


                //跟进信息====================================================================================================

                query.MessageBoardsShowList = (from m in MessageBoardsContract.Entities
                                         join n in StaffContract.Entities
                                         on m.StaffID equals n.Id into tempb
                                         from b in tempb.DefaultIfEmpty()
                                         where m.MessageBoardsType == 3 && m.InterfixID == model.Id && m.IsDeleted == false
                                         select new
                                         {
                                             StaffName = b.Name == null ? "" : b.Name,
                                             Content = m.Content,
                                             CreatedTime = m.CreatedTime
                                         }).ToList()
                                         .Select(m => new MessageBoardsShowModel
                                         {
                                             StaffName =m.StaffName,
                                             Content =m.Content,
                                             CreatedTime =m.CreatedTime.ToString("yy-MM-dd HH:mm")
                                         }).ToList();//跟进信息集合
                
                //佣金====================================================================================================

                //佣金计算
                decimal totalAmount = 0;//应得佣金
                decimal taxAmount = 0;//税款
                decimal achieveAmount = 0;//已结佣金                
                decimal unAchieveAmount = 0;//未结佣金
                int brokerageState = 1;//佣金流水状态

                //应得佣金 参照表BrokerageType
                var brokerageRunningsModel = BrokerageRunningsContract.Entities.Where(m => m.ModuleID == 1 && m.RunningsID == model.Id && m.BrokerageTypeID == 3).FirstOrDefault();
                if (brokerageRunningsModel != null)
                {
                    totalAmount = brokerageRunningsModel.Amount;
                    taxAmount = brokerageRunningsModel.Tax;
                    brokerageState = brokerageRunningsModel.State;

                    var brokerageSettleAccountsRunningsList = BrokerageSettleAccountsRunningsContract.Entities.Where(m => m.BrokerageRunningsID == brokerageRunningsModel.Id).ToList();
                    foreach (var item in brokerageSettleAccountsRunningsList)
                    {
                        achieveAmount += item.Amount;
                    }
                }
                unAchieveAmount = totalAmount - taxAmount - achieveAmount;

                query.TotalAmount = totalAmount.ToString("0.00") + "元";
                query.TaxAmount = taxAmount.ToString("0.00") + "元";
                query.AchieveAmount = achieveAmount.ToString("0.00") + "元";
                query.UnAchieveAmount = unAchieveAmount.ToString("0.00") + "元";
                switch (brokerageState)
                {
                    case 0:
                    case 1:
                        query.BrokerageState = 2;
                        break;
                    case 2:
                    case 3:
                    case 4:
                    case 5:
                        query.BrokerageState = 1;
                        break;
                }
                
                var result = new AjaxResult("成功", AjaxResultType.Success, query);
                return Token(result, "");

            }
            else
            {
                var result = new AjaxResult("失败", AjaxResultType.Error);
                return Token(result, "");
            }

        }




    }
}